package cn.hongwei.service.impl;

import cn.hongwei.entity.Member;
import cn.hongwei.entity.form.MemberRegistForm;
import cn.hongwei.mapper.MemberMapper;
import cn.hongwei.result.ResultCodeEnum;
import cn.hongwei.service.MemberService;
import cn.hongwei.service.base.consts.Keys;
import cn.hongwei.service.base.handler.GuliException;
import cn.hongwei.utils.FormUtils;
import cn.hongwei.utils.MD5;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2021-07-09
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public void saveMember(MemberRegistForm member) {
        //验证必须的参数是否提交
        String mobile = member.getMobile();
        String nickname = member.getNickname();
        String password = member.getPassword();
        String code = member.getCode();
        if(StringUtils.isEmpty(mobile)||
                StringUtils.isEmpty(nickname)||
                StringUtils.isEmpty(password)||
                StringUtils.isEmpty(code)||
                !FormUtils.isMobile(mobile)
        ){
            throw new GuliException(ResultCodeEnum.PARAM_ERROR);
        }
        //1、验证验证码: 用户提交的注册验证码需要和redis中保存的验证码一样
        Object redisCodeObj = redisTemplate.opsForValue().get(Keys.CODE_CODE_KEY + mobile);
        if(!(redisCodeObj!=null && code.equals(redisCodeObj.toString()))){
            //验证码错误
            throw new GuliException(ResultCodeEnum.CODE_ERROR);
        }
        //2、手机号码唯一校验
        LambdaQueryWrapper<Member> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Member::getMobile , mobile);
        Integer count = baseMapper.selectCount(queryWrapper);
        if(count>0){
            //手机号码已被占用
            throw new GuliException(ResultCodeEnum.REGISTER_MOBLE_ERROR);
        }
        //3、保存用户数据到数据库
        Member m = new Member();
        BeanUtils.copyProperties(member , m);
        m.setAvatar("https://sh210225-gulionline.oss-cn-shanghai.aliyuncs.com/avatar/2021/06-29/1624929510122_12fe0d78.jpg");//设置默认头像
        //密码不保存明文，数据库可以被开发和运维以及有服务器管理权限的人员看到
        // SpringSecurity: BCryptPasswordEncoder  提供加密方式，同一个明文每次加密的结果都不一样[加盐]   用户登录时密码的判断必须由该工具类来判断
        // MD5 :相同的明文每次加密的结果都一样，容易被暴力破解[加盐]
        m.setPassword(MD5.encrypt(member.getPassword()));
        baseMapper.insert(m);
        //删除redis中的手机验证码
        redisTemplate.delete(Keys.CODE_CODE_KEY + mobile);
    }
}
